import logging
import pickle
from datetime import datetime
import pytest
from pathlib import Path
from tools.ERP上传 import 库存上传
from tools.page import page_get
from tools.处理excel import update_excel_库存

logger = logging.getLogger(__name__)
date = datetime.now().date().strftime('%Y-%m-%d')


@pytest.mark.flaky(reruns=2, reruns_delay=2, reruns_show_all=True)
@pytest.mark.run(order=1)
def 聚水潭导出库存_test(login_聚水潭, timestamp):
    logger.info('开始操作聚水潭')
    page = page_get(9230, r'C:\\Chromedata_商品库存')
    page.wait(1)
    page.get('https://www.erp321.com/app/item/SkuStock/WmsSkuStock.aspx?_c=jst-epaas')
    page.wait(5)
    已下载仓_list = [] if not Path('./已下载文件.pkl').exists() else pickle.load(open('./已下载文件.pkl', 'rb'))
    发货仓eles = page.eles('._cbb_label')
    for 发货仓ele in 发货仓eles:
        发货仓name = 发货仓ele.text
        if '代发' in 发货仓name or '中转' in 发货仓name or 发货仓name in 已下载仓_list:
            continue
        发货仓ele.click(by_js=True)
        page('.btn_search').click()
        page.wait(2)
        page.set.download_path(f'C:/商品库存/{date}')
        page.set.download_file_name(f'商品库存{发货仓name}.xlsx')
        page('导出（竖向）').click(by_js=True)
        logger.info('等待文件导出')
        page.wait.download_begin(timeout=180)
        page.wait.downloads_done(timeout=180)
        logger.info('导出成功')
        库存上传(f'C:/商品库存/{date}/商品库存{发货仓name}.xlsx', f'商品库存{发货仓name}.xlsx', timestamp)
        发货仓ele.click(by_js=True)
        已下载仓_list.append(发货仓name)
        pickle.dump(已下载仓_list, open('./已下载文件.pkl', 'wb'))
